/**
 * controller_shopcart.js
 * 购物车相关功能控制器
 * 
 * @author 	王中艺	<wangzy_smile@qq.com>
 * @date 	2017-02-20
 */
app.controller('ShopcartList', function($scope, $location, $http, common, wechat){
	//声明变量
	$scope.cart 	= S('shop_cart');
	if(!$scope.cart)
		return false;
	$scope.coupon 	= {code: '', status: 0, amount: 0, tip : ''};

	//初始化JS
    $scope.init_js  = function(){
        common.setTitle('全部课程');
        wechat.wxConfig();
    }

	//移除商品
	$scope.goods_remove 	= function(item){
		delete $scope.cart.list[item.id];
		$scope.cart.amount 	-= item.price;
		$scope.cart.count 	-= 1;
	}

	//监听优惠码变动
	$scope.$watch('coupon.code', function(nVal, oVal){
		if($scope.coupon.status == 1){
			$scope.coupon.status = 0;
			$scope.coupon.tip 	= '无效优惠码!';
		}
	});

	//检测优惠吗
	$scope.check_code 	= function(){
		$scope.coupon.tip 	= '检测中...';
		if(!$scope.coupon.code){
			$scope.coupon.tip 	= '无效优惠码!';
			$scope.coupon.status 	= 0;
			return false;
		}
		var url 	= config.prefix_url+'/Coupon/checkCode?code='+config.code;
		var param 	= {
			'code'	: $scope.coupon.code,
			'amount' : $scope.cart.amount
		}
		$http.post(url, param).success(function(info){
			if(info.code != 1){
				$scope.coupon.status 	= 0;
				$scope.coupon.tip 	= info.data;
			}else{
				$scope.coupon.status 	= 1;
				$scope.coupon.amount 	= info.data.info.amount;
				$scope.coupon.tip 	= '该优惠券可抵消现金'+$scope.coupon.amount+'!';
				$('.am-modal.input-coupon').modal('close');
			}
			// $('.check-code-loading').css('display', 'none');
		});
	}
	
	//发起支付
	$scope.start_pay 	= function(){
		var url 	= config.prefix_url+'/ShopCart/createPay?code='+config.code;
		var param 	= {
			goods_type	: $scope.cart.goods_type,
			goods_ids	: new Array(),
		}
		if($scope.coupon.status == 1){
			param.coupon_code 	= $scope.coupon.code;
		}
		
		for(var k in $scope.cart.list){
			param.goods_ids.push(k);
		}
		$http.post(url, param).success(function(info){
			if(info.code != 1){
				common.dealError(info);
			}else{
				var data 	= info.data;
				console.log('run this');
				wechat.wxPay(
					data.appId, 
					data.timeStamp, 
					data.nonceStr, 
					data.package, 
					data.signType, 
					data.paySign,
					function(){
						common.doAlert('购买成功!');
						common.backAnchor(true);
						return true;
					}
				)
			}
		});
	}
	$scope.init_js();
});